package org.example.ams.service.impl.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.ams.service.system.ISysRoleMenuService;
import org.example.common.constant.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.example.ams.dao.system.ISysRoleMenuDao;
import org.example.ams.entity.system.SysRoleMenu;

import java.util.List;


/**
 * @author cheval
 */
@Service
public class SysRoleMenuServiceImpl implements ISysRoleMenuService {
    @Autowired
    private ISysRoleMenuDao sysRoleMenuDao;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询角色拥有的权限
     * @param roleId
     * @return
     */
    @Override
    public List<SysRoleMenu> queryByRoleId(Integer roleId) {
        return sysRoleMenuDao.selectList(new QueryWrapper<SysRoleMenu>().eq("role_id",roleId));
    }

    /**
     * 更新角色的权限，先删除再插入
     * @param roleId
     * @param menuIds
     * @return
     */
    @Override
    public boolean updateAuth(Integer roleId, Integer[] menuIds) {
        try{
            if (menuIds != null && menuIds.length > 0) {
                sysRoleMenuDao.delete(new QueryWrapper<SysRoleMenu>().eq("role_id",roleId));
                SysRoleMenu sysRoleMenu = null;
                // 1. 更新角色权限
                for (Integer menuId : menuIds) {
                    sysRoleMenu = new SysRoleMenu();
                    sysRoleMenu.setRoleId(roleId);
                    sysRoleMenu.setMenuId(menuId);
                    sysRoleMenuDao.insert(sysRoleMenu);
                }
                // 2. 缓存更新策略 - 删除缓存
                redisTemplate.delete(RedisConstant.NAV_TREE_KEY);
            }
            return true;
        }catch (Exception e) {
            return false;
        }
    }
}
